package com.wing.order.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.service.CellInventoryInoutDetailService;
import com.wing.common.constant.CabAuthCode;
import com.wing.common.utils.JsonResult;
import com.wing.wcabinet.model.entity.WcabCellInventoryInout;
import com.wing.wcabinet.service.WcabCellInventoryInoutDetailService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import com.wing.web.utils.LocaleMessage;
import com.wing.common.utils.PageResult;
import com.wing.order.model.entity.OrderReceiveLoad;
import com.wing.order.model.response.OrderReceiveLoadVO;
import com.wing.order.service.OrderReceiveLoadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.wing.order.model.request.OrderReceiveLoadForm;
import org.springframework.validation.annotation.Validated;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "App-上货管理", tags = "上货管理")
@RestController("appOrderReceiveLoadController")
@RequestMapping("order/app/orderReceiveLoad")
@Slf4j
public class OrderReceiveLoadController {

    @Autowired
    private OrderReceiveLoadService orderReceiveLoadService;
    @Autowired
    private LocaleMessage localeMessage;

    @Autowired
    private CellInventoryInoutDetailService cellInventoryInoutDetailService;

    @Autowired
    private WcabCellInventoryInoutDetailService wcabCellInventoryInoutDetailService;

    @ApiOperation(value = "上货明细", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "demandDetailId", value = "配货需求单明细id", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<OrderReceiveLoadVO> list(
            @RequestParam(name = "page",  defaultValue = "1", required = false) Integer page
            , @RequestParam(name = "limit",  defaultValue = "10", required = false) Integer limit
            , @RequestParam(name = "sort",  defaultValue = "create_time", required = false) String sort
            , @RequestParam(name = "order",  defaultValue = "desc", required = false) String order
            , Long receiveDetailId
            , OrderReceiveLoad.Type type
            , String query
            , OrderReceiveLoadForm.LoadType loadType
            ) {
        Page<OrderReceiveLoadVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("receiveDetailId",receiveDetailId);
        if (type!=null){
            params.put("type",type.getValue());
        }
        if (StringUtils.isNotBlank(query)){
            params.put("query",query);
        }
        if (loadType!=null){
            if (OrderReceiveLoadForm.LoadType.load.equals(loadType)){
                params.put("types",new Integer[]{OrderReceiveLoad.Type.selfLoad.getValue(),OrderReceiveLoad.Type.selfLoadSimple.getValue(),OrderReceiveLoad.Type.selfBatchLoadSimple.getValue()});
            }else{
                params.put("types",new Integer[]{OrderReceiveLoad.Type.selfUnloadSimple.getValue(),OrderReceiveLoad.Type.selfBatchUnloadSimple.getValue()});
            }

        }
        Page<OrderReceiveLoadVO> list = orderReceiveLoadService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/detail/{id}")
    public JsonResult detail(@PathVariable("id") Long orderReceiveLoadId) {
        OrderReceiveLoadVO orderReceiveLoadVO = orderReceiveLoadService.get4appById(orderReceiveLoadId);
        if (orderReceiveLoadVO == null) {
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        return JsonResult.success(localeMessage.getMessage("common.success"), orderReceiveLoadVO);
    }

    @PostMapping()
    public JsonResult add(@Validated OrderReceiveLoadForm orderReceiveLoadForm) {
        if (orderReceiveLoadService.add(orderReceiveLoadForm) > 0) {
            return JsonResult.success(localeMessage.getMessage("common.success"));
        }
        return JsonResult.fail(localeMessage.getMessage("common.fail"));
    }

    @PutMapping()
    public JsonResult update(OrderReceiveLoadForm orderReceiveLoadForm) {
        OrderReceiveLoad orderReceiveLoad =
            orderReceiveLoadService.getOne(new QueryWrapper<OrderReceiveLoad>().eq("id" , orderReceiveLoadForm.getId()));
        if (orderReceiveLoad ==null){
            return JsonResult.fail(localeMessage.getMessage("common.fail" ));
        }
        if (orderReceiveLoadService.updateById(orderReceiveLoad)) {
            return JsonResult.success(localeMessage.getMessage("common.success" ));
        }
        return JsonResult.fail(localeMessage.getMessage("common.fail" ));
    }

    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long orderReceiveLoadId) {
        OrderReceiveLoad orderReceiveLoad =orderReceiveLoadService.getById(orderReceiveLoadId);
        if (orderReceiveLoad ==null){
            return JsonResult.fail(localeMessage.getMessage("common.fail"));
        }
        if (orderReceiveLoadService.removeById(orderReceiveLoadId)) {
            return JsonResult.success(localeMessage.getMessage("common.success"));
        }
        return JsonResult.fail(localeMessage.getMessage("common.fail"));
    }

    @ApiOperation(value = "上货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/loadSimple")
    public JsonResult loadSimple(@Validated(OrderReceiveLoadForm.Add.class) OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            String cabAuthCodes= JwtUtils.getCabAuthCodes();
            if (!cabAuthCodes.contains(CabAuthCode.LOAD_AUTH_CODE)){
                return JsonResult.fail("此用户无上货权限,请配置此用户角色的上货权限");
            }
            cellInventoryInoutDetailService.inventoryIn4Simple(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "上货(柜子面板上)", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/load4Cab")
    public JsonResult load4Cab(@Validated(OrderReceiveLoadForm.Add.class)@RequestBody OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            String cabAuthCodes= JwtUtils.getCabAuthCodes();
            if (!cabAuthCodes.contains(CabAuthCode.LOAD_AUTH_CODE)){
                return JsonResult.fail("此用户无上货权限,请配置此用户角色的上货权限");
            }
            orderReceiveLoadForm.setType(OrderReceiveLoad.Type.selfLoadSimple);
            cellInventoryInoutDetailService.inventoryIn4Simple(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "下货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/unload")
    public JsonResult unload(@Validated(OrderReceiveLoadForm.Add.class) OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            String cabAuthCodes= JwtUtils.getCabAuthCodes();
            if (!cabAuthCodes.contains(CabAuthCode.UNLOAD_AUTH_CODE)){
                return JsonResult.fail("此用户无下货权限,请配置此用户角色的下货权限");
            }
            cellInventoryInoutDetailService.inventoryOut4Simple(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "下货（柜子面板）", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/unload4Cab")
    public JsonResult unload4Cab(@Validated(OrderReceiveLoadForm.Add.class)@RequestBody OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            String cabAuthCodes= JwtUtils.getCabAuthCodes();
            if (!cabAuthCodes.contains(CabAuthCode.UNLOAD_AUTH_CODE)){
                return JsonResult.fail("此用户无下货权限,请配置此用户角色的下货权限");
            }
            orderReceiveLoadForm.setType(OrderReceiveLoad.Type.selfUnloadSimple);
            cellInventoryInoutDetailService.inventoryOut4Simple(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "上货", notes = "上货")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/wcab/load4Cab")
    public JsonResult wcabLoad(@Validated(OrderReceiveLoadForm.Add.class) @RequestBody OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            orderReceiveLoadForm.setType(OrderReceiveLoad.Type.selfLoadSimple);
            orderReceiveLoadForm.setOperationType(WcabCellInventoryInout.OperationType.load);
            wcabCellInventoryInoutDetailService.inventoryIn4Batch(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "补货", notes = "补货")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/wcab/loadAdd4Cab")
    public JsonResult wcabLoadAdd(@Validated(OrderReceiveLoadForm.Add.class) @RequestBody OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            orderReceiveLoadForm.setType(OrderReceiveLoad.Type.replenishment);
            orderReceiveLoadForm.setOperationType(WcabCellInventoryInout.OperationType.supplyIn);
            wcabCellInventoryInoutDetailService.inventoryIn4Batch(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "退货", notes = "退货")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/wcab/return4Cab")
    public JsonResult wcabReturn(@Validated(OrderReceiveLoadForm.Add.class) @RequestBody OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            orderReceiveLoadForm.setType(OrderReceiveLoad.Type.returnToCab);
            orderReceiveLoadForm.setOperationType(WcabCellInventoryInout.OperationType.recycleIn);
            wcabCellInventoryInoutDetailService.inventoryIn4Batch(orderReceiveLoadForm);
            return JsonResult.success("上货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "下货", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/wcab/unload4Cab")
    public JsonResult wcabUnload(@Validated(OrderReceiveLoadForm.Add.class) OrderReceiveLoadForm orderReceiveLoadForm) {
        try{
            wcabCellInventoryInoutDetailService.inventoryOut4Batch(orderReceiveLoadForm);
            return JsonResult.success("下货成功");
        }catch (Exception e){
            log.error("receive load fail",e);
            return JsonResult.fail(e.getMessage());
        }
    }

}
